package cn.edu.cuc.yjsy.admin.dialogs;

import java.sql.SQLException;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import cn.edu.cuc.yjsy.admin.connection.DBConnection;
import cn.edu.cuc.yjsy.admin.util.MessageHelper;
import cn.edu.cuc.yjsy.admin.util.Op;

public class DatabaseLocationPage extends WizardPage {
	
	private static final String ODBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
	private final String[][] databaseType = {
			{"Microsoft Access", "*.mdb", "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};"}};
	private String filePath;
	private Combo dbType;
	private Text fileText;
	private DBConnection connection = null;
	private Combo tableName;
	
	protected DatabaseLocationPage(String pageName, String title,
			ImageDescriptor titleImage) {
		super(pageName, title, titleImage);
		setDescription(MessageHelper.WIZARD_LOCATIONPAGE_DESCRIPTION);
	}

	public void createControl(Composite parent) {
        Composite topLevel = new Composite(parent,SWT.NONE);
        GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		gridLayout.marginWidth = gridLayout.marginHeight = 10;
        topLevel.setLayout(gridLayout);
        topLevel.setLayoutData(new GridData(
                GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
        topLevel.setFont(parent.getFont());
        
        Label l = new Label(topLevel, SWT.NONE);
        GridData data = new GridData();
        data.horizontalSpan = 2;
        l.setLayoutData(data);
        l.setText(MessageHelper.WIZARD_LOCATIONPAGE_DRIVER_LABEL);
        
        dbType = new Combo(topLevel, SWT.READ_ONLY | SWT.DROP_DOWN);
        data = new GridData();
        data.horizontalSpan = 2;
        dbType.setLayoutData(data);
        for(int i = 0; i < databaseType.length; i++)
        	dbType.add(databaseType[i][0]);
        dbType.select(0);
        
        createLine(topLevel, 2);
        
        l = new Label(topLevel, SWT.NONE);
        data = new GridData();
        data.horizontalSpan = 2;
        l.setLayoutData(data);
        l.setText(MessageHelper.WIZARD_LOCATIONPAGE_URL_LABEL);
        
		fileText = new Text(topLevel, SWT.BORDER | SWT.READ_ONLY);
		data = new GridData();
		data.horizontalAlignment = GridData.FILL;
		data.grabExcessHorizontalSpace = true;
		data.widthHint = 300;
		fileText.setLayoutData(data);
		final Button browserButton = new Button(topLevel, SWT.PUSH);
		browserButton.setText(MessageHelper.IMPORT_BROWSER);
		data = new GridData();
		data.horizontalAlignment = GridData.FILL;
		data.grabExcessHorizontalSpace = true;
		browserButton.setLayoutData(data);
		browserButton.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {			
			}
			public void widgetSelected(SelectionEvent e) {
				FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
				fileDialog.setFilterExtensions(getExtensions());
				fileDialog.setFilterNames(getTypeNames());
				String filterPath = fileText.getText();
				if(filterPath != null){
					int last = filterPath.lastIndexOf("\\");
					if(last > 0)
						fileDialog.setFilterPath(filterPath.substring(0, last));
				}
				filePath = fileDialog.open();
				
				fileText.setText(filePath);
				testConnectionUrl();
				
				setPageComplete(isPageComplete());
				getContainer().updateButtons();
			}
			
		});
		
		createLine(topLevel, 2);
		
        l = new Label(topLevel, SWT.NONE);
        data = new GridData();
        data.horizontalSpan = 2;
        l.setLayoutData(data);
        l.setText(MessageHelper.WIZARD_LOCATIONPAGE_TABLE_LABEL);
        
        tableName = new Combo(topLevel, SWT.READ_ONLY);
        data = new GridData();
        data.horizontalSpan = 2;
        tableName.setLayoutData(data);
		tableName.addSelectionListener(new SelectionListener(){
			public void widgetDefaultSelected(SelectionEvent e) {		
			}

			public void widgetSelected(SelectionEvent e) {
				setPageComplete(isPageComplete());
				getContainer().updateButtons();
			}
			
		});
        
		setControl(parent);
	}
	
	private void testConnectionUrl(){
		connection = new DBConnection(ODBC_DRIVER, Op.toLocaleString(getDatabaseUrl()));
		
		try {
			connection.connection();
			
			try {
				tableName.setItems(connection.getTables());
			} catch (SQLException e) {
				setErrorMessage(MessageHelper.WIZARD_LOCATIONPAGE_FETCHTABLE_ERROR);
			}
		} catch (SQLException e) {
			setErrorMessage(MessageHelper.WIZARD_LOCATIONPAGE_CONNECTION_ERROR);
		}finally{
			try {
				connection.dispose();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * @Override
	 */
	public IWizardPage getNextPage() {
		return null;
	}
	
	/**
	 * @Override
	 */
	public boolean canFlipToNextPage() {
		return false;
	}
	
	public boolean isPageComplete() {
		if (getErrorMessage() != null) return false;
		if(isTextNonEmpty(fileText) && tableName.getSelectionIndex() >= 0){
			ConfigurationWizard wizard = (ConfigurationWizard)getWizard();
			wizard.locationCompleted = true;
			return true;
		}
		return false;
	}
	
	public String getDatabaseUrl(){
		return getConnectionType() + "DBQ=" + filePath;
	}
	
	public String getTableName(){
		return tableName.getText();
	}
	
	private void createLine(Composite parent, int ncol) 
	{
		Label line = new Label(parent, SWT.SEPARATOR|SWT.HORIZONTAL|SWT.BOLD);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = ncol;
		line.setLayoutData(gridData);
	}	
	
	private String getConnectionType(){
		String url = null;
		for(int i = 0; i < databaseType.length; i++)
			if(databaseType[i][0].equals(dbType.getText())){
				url = databaseType[i][2];
				break;
			}
		return url;
	}
	
	private String[] getTypeNames(){
		String[] names = new String[1];
		names[0] = dbType.getText();			
		return names;
	}
	
	private String[] getExtensions(){
		String[] extensions = new String[1];
		for(int i = 0; i < databaseType.length; i++){
			if(databaseType[i][0].equals(dbType.getText()))
				extensions[0] = databaseType[i][1];
		}
			
		return extensions;
	}
	
	private static boolean isTextNonEmpty(Text t)
	{
		String s = t.getText();
		if ((s!=null) && (s.trim().length() >0)) return true;
		return false;
	}	
}
